#include<iostream>

#include<stdio.h>

#include<unistd.h>

#include<string>

#include<string.h>

#include<errno.h>

#include<stdlib.h>

#include <sys/types.h>

#include <sys/wait.h>

#define SIZE 1024

using namespace std;

void reader(int arr[2])
{
    close(arr[1]);
    char buffer[SIZE] = {0};
    int cur_fd = arr[0];
    int num = 5;
    while(num--)
    {
        buffer[0] = 0; // 提醒其是字符串
        sleep(1000);
        ssize_t back = read(cur_fd, buffer, SIZE);
        if(back > 0)
        {
            buffer[back] = 0;
            cout << "收到信息：" << buffer << endl;
        }
        else if(back == 0)
        {
            cout << "信息接收完毕。" << endl;
            break;
        }
        else
        {
            perror("read");
            break;
        }
    }
    close(cur_fd);
}

void writer(int arr[2])
{
    close(arr[0]);
    int cur_fd = arr[1];
    char buffer[SIZE] = {0};
    pid_t self = getpid();
    string str = "hello linux";
    int num = 0;
    while(1)
    {
        buffer[0] = 0;
        // snprintf(buffer, SIZE, "%s-%d-%d", str.c_str(), self, num++);
        // write(cur_fd, buffer, strlen(buffer));
        write(cur_fd, "a", strlen("a"));
        cout << num << endl;
        ++num;
        // sleep(1);
    }
    // close(cur_fd);
}

int main()
{
    int ret_num[2];
    int ret = pipe(ret_num);
    if(ret < 0)
    {
        perror("pipe");
        exit(1);
    }
    ret = fork();
    if(ret == 0)
    {
        writer(ret_num);
    }
    else if(ret > 0)
    {
        reader(ret_num);
        int st = 0;
        wait(&st);
        if(WIFEXITED(st))
        {
            cout << "子进程正常退出，退出状态：" << WEXITSTATUS(st) << endl;;
        }
        else
        {
            cout << "子进程异常退出，异常信号：" << WTERMSIG(st) << endl;
        }
    }
    else
    {
        perror("fork");
        exit(1);
    }
    return 0;
}